<template>
  <div id="faceCompare">
    <h1>人脸比对</h1>
    <div class="text">
      <div class="face-to-sql">
        <div class="title">与现有人脸库进行比较</div>
        <p>点击比对后请耐心等待大约三秒</p>
        <div class="face-compare__input">
          <h2>上传人脸</h2>
          <el-upload
            class="upload-demo"
            :show-file-list="false"
            action="#"
            :before-upload="file => onFileChange(file, 'test.png')">
            <el-button size="small" type="primary">上传图片</el-button>
          </el-upload>
          <div v-if="image" class="image-preview">
            <img :src="image" />
          </div>
        </div>
        <el-button type="primary" @click="handleCompareFaces">比对</el-button>
    <div v-if="results" class="results">
      <h2>比对结果</h2>
      <p>{{ results }}</p>
    </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      image: null,
      results: null,  // 修改为null来表示初始化状态
    };
  },
  methods: {
    onFileChange(file, filename) {
      this.image = URL.createObjectURL(file);
      this.uploadImage(file, filename);
      return false;
    },
    async uploadImage(file, filename) {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('filename', filename);

      try {
        await axios.post('http://192.168.33.201:5001/upload-image', formData);
        this.$message.success("图片上传成功");
      } catch (error) {
        this.$message.error("图片上传失败: " + error.message);
      }
    },
    async handleCompareFaces() {
      try {
        const response = await axios.post('http://192.168.33.201:5001/compare-faces');
        if (response.data.success) {
          this.results = response.data.message; // 假设返回结果是一个字符串
          console.log("人脸比对成功", response);
          this.$message.success("人脸比对成功");
        } else {
          this.$message.error("人脸比对失败: " + response.data.error);
        }
      } catch (error) {
        this.$message.error("请求失败: " + error.message);
      }
    }
  }
};
</script>

<style scoped>
#faceCompare {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.text {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.face-to-sql {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 70vh;
  padding: 20px;
  margin: 10px;
  border: 1px solid #ccc;
}

.face-compare__input {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.image-preview img {
  max-width: 100%;
  height: auto;
  border-radius: 5px;
  margin-top: 10px;
}

.results {
  margin-top: 20px;
  width: 100%;
}

.results ul {
  list-style-type: none;
  padding: 0;
}

.results li {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>

